﻿#define DEBUG

//#define GetCurrentUser
//#define DisplayError
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using GCELibrary.Current;
 
using System.Text.RegularExpressions;
using System.Xml.Linq;
using ZF.DAL;
using ZF.BLL;
using System.Web;
using System.Transactions;
using System.Net.Mail;
using System.Threading;
using ZF.BLL.Page;
 
namespace ZF.BLL
{
    /// <summary>
    /// 站点仅用类，该类封装系统中常用的一个API
    /// </summary>
    public partial class SiteInfo
    {

        public SiteInfo()
        {

            if (_exits)
            {
                throw _instance.WarnFactory.CreateWarn("一个站点不能同时存在两个SiteInfo实例");
            }
            _exits = true;
        }

        #region  常量&变量
        private static bool _exits = false;//用于检测当前是否只有一个对象存在
        private static bool _firstRun = true;//首次运行
        private static bool _initSuccess = false;//初始化成功
        private static bool _initIng = false;//初始化中
        private static bool _initDBConnectionSuccess = false;//初始化数据库连接成功
        /// <summary>
        /// 数据库配置文件路径，如果Webconfig中未对DBConfigFile进行配置，则抛出ApplicationException异常
        /// </summary>
        protected string DBConnectionConfigFile
        {
            get
            {
#if(DEBUG)
                Regex rex = new Regex("^.*(\\\\+.*\\\\+)$");
                Match match=rex.Match(System.AppDomain.CurrentDomain.BaseDirectory);
                if (match.Groups.Count != 2) { return null; }
                return System.AppDomain.CurrentDomain.BaseDirectory.Replace(match.Groups[1].Value
                    , "\\ZF.BLL\\DBConfig.xml");
                
                
#else
                var result = System.Configuration.ConfigurationSettings.AppSettings[AppKey.WebConfigKey.DBConfigFile];
                if (result == null)
                    throw new ApplicationException("系统错误，未找到数据库配置文件");
                if (File.Exists(result))
                    return result;
                result = System.Web.HttpContext.Current.Server.MapPath(result);
                if (File.Exists(result))
                    return result;
                return result;
#endif
            }
        }

        private SystemConfig _SystemConfig = null;

        public SystemConfig SystemConfig
        {
            get
            {
                
                if (_SystemConfig == null)
                {
                   
                    var sysConfigFile = System.Configuration.ConfigurationSettings.AppSettings[AppKey.WebConfigKey.SysConfigFile];
                    sysConfigFile=HttpContext.Current.Server.MapPath(sysConfigFile);
                    var txt = "";
                    if (File.Exists(sysConfigFile))
                    {
                        txt = File.ReadAllText(sysConfigFile, Encoding.Unicode);
                    }
                    
                    if (!string.IsNullOrEmpty(txt))
                        _SystemConfig = Newtonsoft.Json.JsonConvert.DeserializeObject<SystemConfig>(txt);
                    else
                    {
                        _SystemConfig = new SystemConfig();
                        _SystemConfig.Save();
                    }
                }
                return _SystemConfig;
            }
        }
        #endregion

        #region Warn相关
        /// <summary>
        /// 报告生成器,该对像可以生成一个异常用于throw
        /// </summary>
        public virtual WarnFactory WarnFactory
        {
            get
            {
                return PageWarnFactory;
                //return Singleton<WarnFactory>.Instance;

            }
        }
        public virtual WarnFactory PageWarnFactory
        {
            get
            {

                if (HttpContext.Current != null && HttpContext.Current.Handler != null && HttpContext.Current.Handler is PageBase)
                {
                    return ((PageBase)HttpContext.Current.Handler).WarnFactory;
                }
                return Singleton<WarnFactory>.Instance;

            }
        }

        Dictionary<Guid, object> _dicPageWarn = new Dictionary<Guid, object>();
        object pageWarnLock = new object();

        /// <summary>
        /// 注册一个页面报告
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public virtual string RegPageWarnContent(string s)
        {
            Guid guid = Guid.NewGuid();
            lock (pageWarnLock)
            {
                _dicPageWarn[guid] = s;
            }
            return guid.ToString();
        }

        public virtual string GetPageWarnContent(string str)
        {
            string result = null;
            Guid guid = str.Convert<Guid>();
            lock (pageWarnLock)
            {
                if (_dicPageWarn.ContainsKey(guid))
                {
                    result = _dicPageWarn[guid].ToString();
                    _dicPageWarn.Remove(guid);
                }
            }
            return result;
        } 


        public virtual void WarnAlert(Exception ex)
        {
            if (ex != null)
            {
                string content = null;
                string title = null;
                WarnBase wb = null;
                if (ex.InnerException is WarnBase && ex.InnerException != null)
                {
                    wb = ((WarnBase)ex.InnerException);
                    if (wb.InnerException != null)
                    {
                        content = wb.InnerException.ToString();
                        title = wb.Message;
                    }
                }
                else if (ex.InnerException != null)
                {

                    content = ex.InnerException.ToString();
                    title = ex.InnerException.Message;
                }
                else
                {
                    content = ex.ToString();
                    title = ex.Message;
                }
                if (content != null && title != null)
                {
                    if (_initDBConnectionSuccess)
                        InsertLog(title, content);
                    else
                        InsertFileLog(ex);
                }
                if (wb == null)
                    wb = WarnFactory.CreateWarn(ex);
                try
                {
                    if(!IsLocal)
                        wb.Alert();
#if(!DisplayError)
                    wb.Alert();
#endif

                }
                catch (Exception _ex)
                {
                    throw _ex;
                }

            }



        }

        #endregion

        #region 数据库相关


        private object _dbConnectionConfigLock = new object();//数据库配置并发锁
        private object _dbConnectionStringLock = new object();//连接字符串并发锁
         private volatile string _dbConnectionStringL = "Data Source=.;Initial Catalog=zfdb;User ID=sa;Password=123456";//数据库的连接字符串
         private volatile string _dbConnectionStringW = "data source=.;User ID=zf;pwd=123456;Initial Catalog=zfdb";//数据库的连接字符串
       private volatile string _dbConnectionStringL1 = "data source=124.172.159.5;User ID=zf;pwd=123456;Initial Catalog=zfdb";//数据库的连接字符串

        public bool IsLocal { get { return File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\bin\_sflag.txt"); } }
        
        private string _dbConnectionString
        {
            get
            {
                //return _dbConnectionStringW;
                if (!IsLocal)
                {
                    return  _dbConnectionStringW;

                }
                else
                {
                    return _dbConnectionStringL;
                    //return _dbConnectionStringL;
                }
 

            }
        }
        /// <summary>
        /// 数据库的连接字符串
        /// </summary>
        public virtual string DBConnectionString
        {
            get
            {
      
                if (_dbConnectionString == null)
                {
                    ReDBConnection();//重置当前系统使用的数据库连接
                }
                return _dbConnectionString;
            }
        }
        /// <summary>
        /// 更新数据库连接配置,该方法只更新配置文件，不更新当前系统使用的数据库连接，
        /// 如果需要更新当前系统使用的数据库连接请调用ReDBConnection方法
        /// </summary>
        /// <param name="xes"></param>
        /// <returns></returns>
        public bool UpdateDBConnectionConfig(XDocument xDoc)
        {
            if (xDoc == null)
                throw WarnFactory.CreateWarn(new ArgumentNullException("参数不能为null值"));
            var existDefault = false;
            if (xDoc.Root.Elements().Count() == 0)
                throw WarnFactory.CreateWarn(new ArgumentNullException("数据库配置错误,连接配置不能少于一条"));
            var xeList = XmlHelper.GetXElement(xDoc, "/connectionStrings/add");
            foreach (var xe in xeList)
            {
                if (xe.Attribute("name") == null || xe.Attribute("connectionString") == null || xe.Attribute("isDefault") == null)
                {
                    throw WarnFactory.CreateWarn(new ArgumentNullException("参数格式错误"));
                }
                if (xe.Attribute("isDefault").Value != "0")
                {
                    if (existDefault)
                        throw WarnFactory.CreateWarn(new ArgumentNullException("数据库配置错误，默认连接不允许多个"));
                    else
                        existDefault = true;
                }
            }
            if (!existDefault)
                throw WarnFactory.CreateWarn(new ArgumentNullException("数据库配置错误，不存在默认连接"));
            return SetDBConnectionConfigFile(xDoc);//更新到配置文件
        }
        /// <summary>
        /// 返回数据库连接配置文件的所有配置节点
        /// </summary>
        /// <returns></returns>
        public XDocument GetDBConnectionConfig()
        {
            var xDoc = GetDBConnectionConfigFile();
            return xDoc;
        }
        /// <summary>
        /// 重置当前系统使用的数据库连接，一般在更新数据库配置（文件）后调用该方法
        /// </summary>
        public void ReDBConnection()
        {
            return;
            //var conn = GetDefaultDBConnection();
            //bool needInit = false;//判断是否需要重新初始化

            //lock (_dbConnectionStringLock)
            //{
            //    if (conn != _dbConnectionString)
            //    {
            //        needInit = true;
            //        _dbConnectionString = conn;
            //    }
            //    //_dbConnectionString = conn;
            //}
            //if (needInit && !_initIng)
            //    Init();
        }
        private bool CheckDBConnection()
        {
            bool result = false;
            using (var dc = CreateDBDataContext())
            {
                try
                {
                    dc.Connection.Open();
                    result = true;
                }
                catch (Exception ex)
                {

                }
            }
            return result;
        }
        /// <summary>
        /// 生成数据库操作对象
        /// </summary>
        /// <returns></returns>
        public static  ZFDataContext CreateDBDataContext()
        {
            return CreateDBDataContext(_instance.DBConnectionString);
        }
        /// <summary>
        /// 生成数据库操作对象，connection为连接字符串
        /// </summary>
        /// <returns></returns>
        public static ZFDataContext CreateDBDataContext(string connection)
        {

            return new ZFDataContext(connection);
        }
        #endregion
 
        #region 日志

        private bool _initFileLogConfig = false;

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="ex"></param>
        public void InsertLog(Exception ex)
        {
            InsertLog(ex.Message, ex.ToString());
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public void InsertLog(string title, string content)
        {
            InsertLog(title, content, 0);
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public void InsertLog(string title, string content, int type)
        {
            try
            {
                using (var dc = CreateDBDataContext())
                {
                    dc.Sys_Log.InsertOnSubmit(new Model.Sys_Log()
                    {
                        Content = content,
                        CreateTime = DateTime.Now,
                        Type=type,
                        Title = title,
                    });
                    dc.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                InsertFileLog(new Exception("插入日志错误", ex));
            }
        }
        /// <summary>
        /// 写入文件日志,该方法未开发
        /// </summary>
        /// <param name="ex"></param>
        public void InsertFileLog(Exception ex)
        {
            if (!_initFileLogConfig)
            {
                _initFileLogConfig = true;
                var logConfig = System.AppDomain.CurrentDomain.BaseDirectory + "\\log4net.xml";
                log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(logConfig));
            }
            var log = log4net.LogManager.GetLogger("Default");
            try
            {
                if (ex.InnerException != null)
                {
                    log.Error(ex.ToString());
                    log.Error(ex.InnerException.ToString());
                }
                else
                    log.Error(ex.ToString());
            }
            catch (Exception _ex)
            {
            }

        }
        #endregion

        #region 实例

        private static SiteInfo _instance = Singleton<SiteInfo>.Instance;

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static SiteInfo Instance
        {
            get
            {
                if (_firstRun)
                {
                    _firstRun = false;
                    return _instance;
                }
                else if (_initSuccess || _initIng)
                {
                    return _instance;
                }
                else
                {
                    return _instance;
                    _instance.WarnAlert(new Exception("站点初始化错误，请联系系统管理员"));
                    throw new Exception("SiteInfo初始化错误");
                    //return _instance;
                }
            }  
        }
        #endregion

        #region 系统初始化 
        public void Init()
        { 
            if(false)//if (this.NeedSetup)//如果配置了需要安装则首次初始化时转到安装页面
            {
                System.Web.HttpContext.Current.Response.Redirect("~/setup.aspx");
            }
            else
            {
           
                try
                {
                    //if (_initSuccess)//把所有用户踢下线。。
                    //    OnlineUserManage.ClearOnlineUser();
                    _initSuccess = false;
                    _initIng = true;

                    ReDBConnection();//设置数据库连接
                    if (!CheckDBConnection())
                    {
                        throw new Exception("系统初始化时连接数据库失败!");
                    }
                    _initDBConnectionSuccess = true;
                    //ModuleRightConfig.Init();//初始化模块 
                    //this.SystemConfig.Init();
                    _initSuccess = true; 
                    _initIng = false;
                }
                catch (Exception ex)
                {
                    
                    _initSuccess = false;
                    _initIng = false;
                    WarnAlert(WarnFactory.CreateWarn(ex));
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 出现初始化异常时调用该方法进行重新初始化，该方法只允许在初始化异常时调用
        /// </summary>
        public static void ErrReInit()
        {

            if (!_initSuccess && !_initIng)
                _instance.Init();
            else
                throw _instance.WarnFactory.CreateWarn("无权执行该操作");
        }
        /// <summary>
        /// 重置站点的数据配置,该方法一般在
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static bool ResetSiteDBConnConfig(string xml)
        {
            throw new Exception();
            //var result = false;
            //xml = _instance.DecryptBase64(xml);
            //System.Xml.Linq.XDocument xDoc = null;
            //try
            //{
            //    xDoc = System.Xml.Linq.XDocument.Parse(xml);
            //    _instance.UpdateDBConnectionConfig(xDoc);
            //    _instance.ReDBConnection();
            //    result = true;
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}
            //return result;
        }
        #endregion

        #region 内部方法

        #region 数据库
        /// <summary>
        /// 获取默认的数据库连接
        /// </summary>
        /// <returns></returns>
        private string GetDefaultDBConnection()
        {
            throw new Exception();
 
            //var xDoc = GetDBConnectionConfigFile();//获取配置文件
            ////获取默认配置节点
            //var xe = XmlHelper.GetFirstXElement(xDoc, XmlHelper.GetXPath("add", "isDefault", "1", XmlRange.All));
            //if (xe != null && xe.Attribute("connectionString") != null)
            //{
            //    return xe.Attribute("connectionString").Value;
            //}
            //else
            //{
            //    throw WarnFactory.CreateWarn("系统错误,未找到默认数据库连接，请联系系统管理员");
            //}
        }
        /// <summary>
        /// 获取数据库配置文件
        /// </summary>
        /// <returns></returns>
        private XDocument GetDBConnectionConfigFile()
        {
            string path = DBConnectionConfigFile;
            if (!File.Exists(path))
                throw new FileNotFoundException("系统错误,未找到数据库配置文件，请联系系统管理员");
            XDocument xDoc = null;
            lock (_dbConnectionConfigLock)
            {
                try 
                {
                    xDoc = XDocument.Load(path);
                }
                catch (Exception ex)
                {
                    throw WarnFactory.CreateWarn(ex);
                }
            }
            return xDoc;
        }
        /// <summary>
        /// 更新设置数据库配置文件
        /// </summary>
        /// <param name="xDoc"></param>
        /// <returns></returns>
        private bool SetDBConnectionConfigFile(XDocument xDoc)
        {
            //if(!File.Exists(DBConnectionConfigFile))
            //    throw WarnFactory.CreateWarn("系统错误,未找到数据库配置文件",WarnLevel.Error);
            bool isSuccess = true;
            lock (_dbConnectionConfigLock)
            {
                try
                {
                    var fi = new FileInfo(DBConnectionConfigFile);
                    if (fi.Exists)
                        fi.IsReadOnly = false;

                    xDoc.Save(DBConnectionConfigFile);
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    throw WarnFactory.CreateWarn(ex);
                }
            }
            return isSuccess;
        }
        #endregion


        #endregion

        #region 用户 
        /// <summary>
        /// 获取当前登录的用户信息
        /// </summary>
        /// <returns></returns> 
        public virtual IMember GetCurrentMember()
        {
            IMember user = null;
            try
            {

                //从session到获取对像
                object obj = HttpSession.GetSession(AppKey.SessionKey.CurrentUser);
                if (obj is IMember && obj != null)//判断对像是否为空以及对像的类型 
                    user = (IMember)obj;
            }
            catch (Exception ex)
            { 
                throw this.WarnFactory.CreateWarn(ex);
            }
            if (user == null)
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    var cookies = System.Web.HttpContext.Current.Request.Cookies;
                    if (cookies != null)
                    {
                        var cookie = cookies[AppKey.CookieKey.Token];
                        if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                        {
                            var account = cookie.Values[AppKey.CookieKey.Account];
                            var password = cookie.Values[AppKey.CookieKey.Passowrd];
                            if (!string.IsNullOrEmpty(password))
                                password = this.DecryptBase64(password);
                            var gate = new Gate.ManageGate();
                            //var gate = new Gate.GeneralGate();
                            gate.DefaultPage = HttpContext.Current.Request.Url.ToString();
                            var success = gate.Login(account, password, -1);
                            if (success)
                                user = (IMember)HttpSession.GetSession(AppKey.SessionKey.CurrentUser);
                            else
                                gate.RemoveCookie();
                        
                        }
                    }
                }
            }
            return user;
            
        }

        public bool RegisterMember(Model.US_Member member, string recommend)
        {
            using (var dc = CreateDBDataContext())
            {
                try
                {
                    if (!string.IsNullOrEmpty(recommend))
                    {
                        var rmdMember = dc.US_Member.FirstOrDefault(p => p.Account == recommend);
                        if (rmdMember != null)
                        {
                            IntegralLog(rmdMember.MemberId, "推荐注册用户赠送积分", -SystemConfig.JFRecommend);
                        }
                    }
                    dc.US_Member.InsertOnSubmit(member);
                    dc.SubmitChanges();
                    if (SystemConfig.JFReg > 0)
                    {
                        IntegralLog(member.MemberId, "注册赠送积分", -SystemConfig.JFReg);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    throw WarnFactory.CreateWarn(ex);
                }
            }

        }

        public bool CheckRegisterAccount(string account)
        {
            using (var dc = CreateDBDataContext())
            {
                return dc.US_Member.FirstOrDefault(p => p.Account == account) == null;
            }
        }
        public bool CheckRegisterEmail(string email)
        {
            using (var dc = CreateDBDataContext())
            {
                return dc.US_Member.FirstOrDefault(p => p.Email == email) == null;
            }
        }

        public bool GetPwd(string account, string email)
        {
            using (var dc = CreateDBDataContext())
            {
                var member = dc.US_Member.FirstOrDefault(p => p.Account == account && p.Email == email);
                if (member != null)
                {
                    var gp=SystemConfig.GetPwdEmail;
                    var msg=gp.MsgTemplate.Replace("{Account}",member.Account)
                        .Replace("{SiteName}",SystemConfig.SiteName).Replace("{Pwd}",member.Pwd);

                    return SendEmail(msg, string.Format("{0}取回密码", SystemConfig.SiteName),
                        gp.Email, member.Email, gp.Stmp, gp.Account, gp.Pwd);
                }
                else
                    return false;
            }
        }


        #endregion

        #region 加密
        /// <summary>
        ///  密码加密，可逆
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string EncryptPWD(string pwd)
        {
            return EncryptPWD(pwd, "zf");
        }
        /// <summary>
        ///  密码加密，可逆
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string EncryptPWD(string pwd, string key)
        {
            return Cryptography.Encrypt(pwd, key);
        }
        /// <summary>
        /// 密码解密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string DecryptPWD(string pwd)
        {
            return DecryptPWD(pwd, "zf");
        }
        /// <summary>
        /// 密码解密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string DecryptPWD(string pwd, string key)
        {
            return Cryptography.Decrypt(pwd, key);
        }
        /// <summary>
        /// 加密，可逆
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string EncryptBase64(string value)
        {
            string encryptText = Convert.ToBase64String(Encoding.Default.GetBytes(value));
            return encryptText;
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string DecryptBase64(string value)
        {
            string decryptText = Encoding.Default.GetString(Convert.FromBase64String(value));
            return decryptText;
        }
        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="aPwd">要加密的密码</param>
        /// <returns>加密后的密码字符串</returns>
        public string EncodeMD5(string passWord)
        {
            return Cryptography.EncodeMD5(passWord);

        }
        #endregion

        

        #region 房
        public string GetHouseTitle(int id)
        {
            string result = "房源信息";
            switch (id)
            {
                case 1: result = "整租" + result; break;
                case 2: result = "合租" + result; break;
                case 3: result = "二手" + result; break;
                case 4: result = "一手" + result; break;
            }
            return result;
        }
        public string GetHouseDelt(int id)
        {
            string result = "";
            switch (id)
            {
                case 1: result = "整租" + result; break;
                case 2: result = "合租" + result; break;
                case 3: result = "二手" + result; break;
                case 4: result = "一手" + result; break;
            }
            return result;
        }
        #endregion
        



        #region 方法
        /// <summary>
        /// 通过stmp将发送邮件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="title"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="stmp"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public   bool SendEmail(string msg, string title, string from, string to, string stmp, string account, string pwd)
        {
            try
            {
                MailMessage Mail = new MailMessage();
                Mail.From = new MailAddress(from);//发邮件人地址(站长) 
                Mail.To.Add(new MailAddress(to));//目标地址(客户) 
                Mail.Subject = title;//邮件标题 
                Mail.Body = msg;  //要发的邮件内容 
                SmtpClient smtp1 = new SmtpClient(stmp);
                smtp1.Credentials = new System.Net.NetworkCredential(account, pwd);
                smtp1.Send(Mail);
            }
            catch (Exception exp)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool ValidateCode(string str)
        {
            if (IsLocal) return true;

            if (string.IsNullOrEmpty(str))
                return false;
            else
            {
                var objCode = HttpSession.GetSession(BLL.AppKey.SessionKey.ValidateCodeKey);
                return string.Concat(objCode).EqIgnoreCase(str);
            }

        }
        /// <summary>
        /// 验证是否包含过滤关键字
        /// </summary>
        /// <param name="o"></param>
        public void CheckFilterWords(object o)
        {

            if (o != null)
            {
                string str = "";
                var type = o.GetType();
                var pis = type.GetProperties();
                foreach (var pi in pis)
                {
                    if (pi.PropertyType == typeof(string))
                    {
                        str += "|" + string.Concat(pi.GetValue(o, null));
                    }
                }
               
                foreach (var w in SystemConfig.FilterWords)
                {
                    if (str.Contains(w))
                    {

                        throw PageWarnFactory.CreateWarn("包含非法关键字:" + w);
                    }
                }
            }



        }

        /// <summary>
        /// 获取默认地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Model.Dic_Area GetAreaOrDefault(int id)
        {
            var area = DictionaryConfig.HArea.FirstOrDefault(p => p.AreaId == id);
            if (area == null)
                area = DictionaryConfig.HArea.First();
            return area;
        }
        #endregion



        #region Game
        /// <summary>
        /// 购买拜佛供品
        /// </summary>
        /// <param name="oid">供品id</param>
        /// <param name="bId">佛祖id</param>
        /// <param name="x">客户端坐标x</param>
        /// <param name="y">客户端坐标y</param>
        /// <param name="msg">文字</param>
        /// <returns>如果为true字符则为成功，否则返回结果为错误的描述</returns>
        public bool BuyGongPin(int oid, int bId,int x,int y,string msg,out string result)
        {
            var member = BLL.SiteInfo.Instance.GetCurrentMember();
            if (member == null)
            {
                 result="请登录后操作";
                 return false;
                   
            }
            else
            {

                using (var dc = BLL.SiteInfo.CreateDBDataContext())
                {

                    var offering = dc.G_Offering.FirstOrDefault(p => p.OfferingId == oid);

                    var buddha = dc.G_Buddha.FirstOrDefault(p => p.BuddhaId == bId);
                    if (buddha == null)
                    {
                        result = "操作失败";
                        return false;
                    }
                    if (offering == null)
                    {
                        result = "未找到该供品";
                        return false;
                    }
                    bool success = false;
                    try
                    {
                        success = IntegralLog(member.MemberId, "购买供品", offering.Memoy);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (!success)
                    {
                        result = "您的积分不足购买该供品";
                        return false;
                    }
                    var bowing = new ZF.Model.G_Bowing()
                            {
                                AddTime = DateTime.Now,
                                BuddhaId = bId,
                                MemberId = member.MemberId,
                                Msg = msg,
                                X = x,
                                Y = y,
                                Path = offering.Path,
                            };
                    dc.G_Bowing.InsertOnSubmit(bowing);
                    dc.SubmitChanges();

                    result = bowing.BowingId.ToString();
                    return true;




                }
                
            }
 

        }
        /// <summary>
        /// 向佛祖许愿
        /// </summary>
        /// <param name="bid">佛祖id</param>
        /// <param name="msg">许愿内容</param>
        /// <returns></returns>
        public bool Wishing(int bid, string msg, out string result)
        {
            var member = BLL.SiteInfo.Instance.GetCurrentMember();
            if (member == null)
            {
                result = "请登录后操作";
                return false;

            }
            else
            {
                bool success = false;
                try
                {
                    var msglen = msg.Length;
                    var money = 0;
                    var JFBFJF = SystemConfig.JFBFJF;
                    if (JFBFJF.BaseZC < msglen)
                    {
                        var cl = msglen - JFBFJF.BaseZC;
                        var dz = (int)(cl / JFBFJF.BFDZZC) * JFBFJF.BFDZJF;

                        if (cl % JFBFJF.BFDZZC > 0)
                        {
                            dz += JFBFJF.BFDZJF;
                        }
                        money = JFBFJF.BaseJF + dz;

                    }
                    else
                    {
                        money = JFBFJF.BaseJF;
                    }


                    success = IntegralLog(member.MemberId, "在线许愿", money);
                }
                catch (Exception ex)
                {
                }

                if (!success)
                {
                    result = "您的积分不足";
                    return false;
                }
                else
                {



                    using (var dc = BLL.SiteInfo.CreateDBDataContext())
                    {

                        var wishing = new ZF.Model.G_Wishing()
                        {
                            AddTime = DateTime.Now,
                            BuddhaId = bid,
                            Content = msg,
                            MemberId = member.MemberId,

                        };
                        dc.G_Wishing.InsertOnSubmit(wishing);
                        dc.SubmitChanges();
                        result = msg + " " + DateTime.Now.ToShortDateString();
                        return true;
                     

                    }
                }

            }

        }

        #endregion

        private Dictionary<string, DateTime> dicCacheKey = new Dictionary<string, DateTime>();
        private bool _firstSetPageCache = true;
        public void SetPageCache(string cacheKey, object value)
        {
            if (_firstSetPageCache)
            {
                _firstSetPageCache = false;
                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckPageCacheThread));
            }
            dicCacheKey[cacheKey] = DateTime.Now;
            HttpCache.SetCache(cacheKey, value);
        }
        private void CheckPageCacheThread(object o)
        {
            while (true)
            {
                try
                {
                    foreach (var item in dicCacheKey.ToList())
                    {
                        if (item.Value.Add(SystemConfig.DefCacheTimeSpan) < DateTime.Now)
                        {
                            HttpCache.Remove(item.Key);
                            dicCacheKey.Remove(item.Key);
                        }
                    }
                }
                catch (Exception ex) { }
                Thread.Sleep(1000 * 60);
            }
        }
        #region 积分购买记录
        public bool IntegralLog(int memberId, string log, int integra)
        {
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var member = dc.US_Member.FirstOrDefault(p => p.MemberId == memberId);
                if (member == null)
                {
                    throw WarnFactory.CreateWarn("未找到该用户");
                }
                if (member.Integral >= integra)
                {
                    member.Integral = member.Integral - integra;
                    dc.US_IntegralLog.InsertOnSubmit(new ZF.Model.US_IntegralLog()
                    {
                        MemberId = memberId,
                        Title = log,
                        Integral = integra,
                        AddTime = DateTime.Now,

                    });
                    dc.SubmitChanges();
                    var sm = GetCurrentMember();
                    if (sm!=null && sm.MemberId == memberId)
                    {
                        sm.Integral = member.Integral;
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        #endregion
    }

    /// <summary>
    /// 站点类型
    /// </summary>
    public enum SiteType
    {
        None = 0,
        ManageSite,
        MonitorSite,
    }

    public enum ModuleType
    {
        None=0,
        [DescriptionAttribute(Name="系统管理员管理",Description="包括，增加，删除系统管理员，设置权限等")]
        /// <summary>
        /// 系统管理员管理
        /// </summary>
        SysAdmin,
        [DescriptionAttribute(Name = "系统日志浏览")]
        SysLog,
        [DescriptionAttribute(Name = "系统参数设置")]
        SysSetup,
        [DescriptionAttribute(Name = "普通会员管理")]
        /// <summary>
        /// 普通通会员
        /// </summary>
        MMember,
        [DescriptionAttribute(Name = "专家会员管理")]
        /// <summary>
        /// 专家会员
        /// </summary>
        ZJMember,
        [DescriptionAttribute(Name = "积分统计")]
        /// <summary>
        /// 积分统计
        /// </summary>
        JFTJ,
        [DescriptionAttribute(Name = "新闻资讯管理")]
        SysNews,
        [DescriptionAttribute(Name = "房源管理", Description = "包括房源出租，出售，求租，求购，楼盘管理")]
        House,
        [DescriptionAttribute(Name = "商品管理", Description = "包括设置商品类别，发布商品管理等操作")]
        S_Shop,
        [DescriptionAttribute(Name = "订单管理", Description = "对已达成的订单进行管理")]
        S_Order,
        [DescriptionAttribute(Name = "网站服务信息管理", Description = "(按揭/抵押)贷款,房地产交易过户,我要装修,预订机票,风水业务,网站留言,合作加盟")]
        Service,
        [DescriptionAttribute(Name = "在线礼佛设置", Description = "设置佛祖，贡品等信息")]
        /// <summary>
        /// 在线礼佛
        /// </summary>
        LF,
        [DescriptionAttribute(Name = "分类信息管理")]
        Info,
        [DescriptionAttribute(Name = "推荐商家管理")]
        Company,
        [DescriptionAttribute(Name = "广告管理")]
        Ads,
        [DescriptionAttribute(Name = "友情连接管理")]
        FLink,
        [DescriptionAttribute(Name = "博客设置")]
        Blog
    }
 


}
